package com.student.dao.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.student.dao.UserDao;
import com.student.entity.User;
import com.student.template.JdbcTemplate;

public class UserDaoImpl implements UserDao {

	@Override
	public void save(User user) {
		JdbcTemplate<User> jdbcTemplate = new JdbcTemplate<>();
		jdbcTemplate.update((conn) -> {
			PreparedStatement pst = null;
			String sql = "insert into user(uname, upassword) values(?,?)";
			pst = conn.prepareStatement(sql);
			pst.setString(1,user.getUname());
			pst.setString(2, user.getUpassword());
			pst.executeUpdate();
		});

	}

	@Override
	public User findUserByName(String uname) {
		JdbcTemplate<User> jdbcTemplate = new JdbcTemplate<>();
		return jdbcTemplate.query((conn) -> {
			PreparedStatement pst = null;
			ResultSet rs = null;
			User user = null;
			try {
				String sql = "select * from user where uname = ?";
				pst  = conn.prepareStatement(sql);
				pst.setString(1, uname);
				rs = pst.executeQuery();
				if(rs.next()) {
					user = new User();
					user.setId(rs.getInt("id"));
					user.setUname(rs.getString("uname"));
					user.setUpassword(rs.getString("upassword"));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} 
			return user;
		});
	}

}
